﻿using System;
using System.Windows.Forms;

using Moe.ECamel.Client.Controllers;
using Moe.ECamel.Client.WinForms.Common;
using Moe.ECamel.Common.Entities;

namespace Moe.ECamel.Client.WinForms.Forms
{
	public partial class CustomerDetailsForm : ECamelForm
	{
		private readonly EntityDetailsController<Customer> _controller;

		public CustomerDetailsForm()
		{
			InitializeComponent();
		}

		public CustomerDetailsForm(EntityDetailsController<Customer> controller)
			:this()
		{
			this._controller = controller;

			switch (_controller.Mode)
			{
				case DetailsMode.Create:
					this.Text = "הוספת לקוח חדש";
					break;
				case DetailsMode.Edit:
					this.Text = "עריכת פרטי לקוח - " + _controller.Entity.User.FullName;
					break;
				case DetailsMode.View:
				default:
					this.Text = "פרטי לקוח - " + _controller.Entity.User.FullName;
					break;
			}

			this.DetailsControl.Initialize(controller.Entity, controller.Mode);

			ApplyPermissions();
		}

		private void ApplyPermissions()
		{
			if (_controller.Mode == DetailsMode.View)
			{
				ConfirmationButton.Visible = false;
				CancellationButton.Text = "יציאה";
			}
		}

		private void CancellationButton_Click(object sender, EventArgs e)
		{
			this.DetailsControl.CancelEdit();
			this.Close();
		}
		private void ConfirmationButton_Click(object sender, EventArgs e)
		{
			if (ApplyChanges())
			{
				this.DialogResult = DialogResult.OK;
				this.Close();
			}
		}

		private bool ApplyChanges()
		{
			ECamelError error = this._controller.Entity.Validate();
			if (error != null)
			{
				ECamelHelper.ShowMessage(error);
				return false;
			}
			error = this._controller.SubmitChanges();
			if (error != null)
			{
				ECamelHelper.ShowMessage(error);
				return false;
			}

			return true;
		}
	}
}
